<template>
  <div class="aside-right" ref="asideRight" id="asideRight">
    <div class="aside-right_write" v-show="!beginEditorButton">
      <div class="aside-right_header">
        <input v-model="title" @blur="handerTitleBlur" @focus="handleTitleFocus" :placeholder="titlePlaceholder"
               maxlength="30"/>
        <!--<img class="set-scale" src="@/assets/images/scale.png" @click="showLargeEditor" />-->
        <span class="set-scale" @click="showLargeEditor">
					<svg class="icon" aria-hidden="true" v-show="!maximization">
					  	<use xlink:href="#icon-maximize"></use>
					</svg>
					<svg class="icon" aria-hidden="true" v-show="maximization">
					  	<use xlink:href="#icon-minimize"></use>
					</svg>
				</span>

      </div>
      <div class="quill-box">
        <quill-editor ref="newEditor" :options="editorOption" v-model="editorContent"
                      @blur="onEditorBlur($event)"
                      @focus="onEditorFocus($event)"
                      @ready="onEditorReady($event)"
                      @change="onEditorChange($event)">
        </quill-editor>
      </div>
      <aside-right-bottom></aside-right-bottom>
    </div>
    <!--新增 无内容提示-->
    <div class="nocontent-tips" v-show="beginEditorButton">
      <img src="../../assets/images/no-content.png"/>
      <p>摛文掞藻，从这里开始</p>
      <div class="aside-right_null">
        <div @click="handleBeginClick">开始写文章</div>
      </div>
    </div>

  </div>
</template>

<script>
  import {mapState, mapActions} from 'vuex';
  import util from '@/lib/util';
  import vueQuillEditor from 'vue-quill-editor'
  import Quill from 'quill'
  import AsideRightBottom from './ArticleRightBottom'
  import {ImageImport} from '../modules/ImageImport.js'
  import {ImageResize} from '../modules/ImageResize.js'

  Quill.register('modules/imageImport', ImageImport);
  Quill.register('modules/imageResize', ImageResize);

  export default {
    name: 'AsideRight',
    components: {
      vueQuillEditor,
      AsideRightBottom
    },
    data() {
      return {
        uniqueId: '',
        maximization: false,
        titlePlaceholder: "请输入文章标题",
        editorOption: {
          placeholder: '',
          modules: {
            history: {
              delay: 2000,
              maxStack: 500,
              userOnly: false
            },
            toolbar: [
              [{'header': [1, 2, 3, 4, 5, 6, false]}],
              [{
                'size': ['small', false, 'large', 'huge']
              }],
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote'],
              [{
                'color': []
              }, {
                'background': []
              }], // dropdown with defaults from theme
              [{
                'font': ['微软雅黑', 'Arial', '宋体', '黑体', 'Georgia']
              }],
              [{
                'list': 'ordered'
              }, {
                'list': 'bullet'
              }],
              ['link', 'video'],
              ['clean']
            ],
            imageImport: true,
            imageResize: {
              displaySize: true
            },
          },
          strict: false
        },
        title: '',//编辑的文章标题
        editorContent: '',//文章内容
        editorTitle: '',//??????
        addImgRange: '', //全局参数，每次添加图片时记录当前索引和长度
        isShow: true, //控制样式?????
        imageLoading: false,//设置图片是否在加载中
        url: '',
        isfirst: true,
        editorContentCount: 0//编辑的字数
      }
    },
    created() {

    },
    computed: {
      ...mapState([
        'articleDetail',
        'beginEditorButton',//控制是否显示开始写文章按钮
        'chooseArticleImg',   // 图片素材
        'isfromAddimg',
        'folderId',
        'articleList',
        'previewInfo'
      ])
    },
    watch: {
      articleDetail() {
        // 判断是否articleDetail为空对象
        let ad = this.articleDetail || {content: '', title: ''};
        this.editorContent = ad.content;
        this.title = ad.title;
        // 首次文字count
        if (!this.editorContent) return;
        let content = this.editorContent.replace(/<p><br><\/p>/g, '');
        this.editorContentCount = parseInt(content.length / 20) || 0
      },
      'chooseArticleImg'() {
        if (this.isfromAddimg) {
          this.url = this.chooseArticleImg.url;
          // 只有在添加图片组件里变化的img,才走插入图片
          this.init();
        }
      },
      articleList(curVal, oldVal) {

        let curlist = this.articleList || [];
        if (curlist.length == 0) {
          this.changgeBeginEditorButton(true);
        }
      }
    },
    methods: {
      ...mapActions([
        'fetchArticleList',
        'changgeBeginEditorButton',
        'handleShowsetCover',
        'clearChoeseImg',
        'handleisFromAddImg',
        'activeArticle',
        'handleshowPreviewLayer',
        'haddleSetPreviewInfo',
        'newArticle',
      ]),
      //最大化按钮处理事件
      showLargeEditor() {
        let asideleft = document.getElementById("asideleft");
        let asidecenter = document.getElementById("asidecenter");
        let open = document.getElementById("open");
        if (!this.maximization) {
          this.$refs.asideRight.style.left = '0px';
          this.$refs.asideRight.style.zIndex = '1000';
          this.maximization = true;
        } else {
          if (open.style.display == 'block') {
            this.$refs.asideRight.style.left = '302px';
            this.$refs.asideRight.style.zIndex = '10';
            this.maximization = false;
          } else {
            this.$refs.asideRight.style.left = '522px';
            this.$refs.asideRight.style.zIndex = '10';
            this.maximization = false;
          }
        }
      },
      //开始写文章按钮处理事件
      handleBeginClick() {
        this.changgeBeginEditorButton(false);
        let that = this;
        this.newArticle({'folderId': this.folderId}).then((res) => {
          let paramsValue = {
            'pageNo': 1,
            'folderId': this.folderId
          };
          this.fetchArticleList(paramsValue).then((res) => {
            that.activeArticle(res.data.articleId);
          });
        });
      },
      //编辑器初始化
      init() {
        let vm = this;
        vm.addImgRange = vm.$refs.newEditor.quill.getSelection(true);
        vm.imageLoading = true;
        try {
          // 单个上传逻辑
          const urlList = this.url;
          let value = urlList;
          value = value.indexOf('http') != -1 ? value : 'http:' + value; //返回图片网址中如果没有http自动拼接
          let index = vm.addImgRange != null ? vm.addImgRange.index : 0; // 获取插入时的位置索引，如果获取失败，则插入到最前面
          vm.$refs.newEditor.quill.insertEmbed(index, 'image', value, Quill.sources.USER);
          let img = new Image();
          img.src = value;
        } catch ({
          message: msg
        }) {
        }
        vm.imageLoading = false
      },
      uploadImg(id) {
        // 清除所选的值
        this.clearChoeseImg();
        this.handleisFromAddImg(true);
        this.handleShowsetCover(true);
      },
      onEditorBlur({
                       quill,
                       html,
                       text
                     }) {


      },
      onEditorFocus(quill) {

      },
      onEditorReady(quill) {

      },
      onEditorChange({
                       quill,
                       html,
                       text
                     }) {
        this.editorContent = html;

        //尽量不要用localStorage
        //localStorage.setItem('textContent', text);
        //必须放在这里，否则会造成previewInfo中的editorHtml为空，点击保存按钮的时候出现正文保存内容为空
        this.haddleSetPreviewInfo({
          title: this.title,
          textContent:text,
          editorHtml: html,
          tags: '',
          ceateTime: new Date().getTime() // 当前时间
        });

        // 每编辑20字 自动发送一次更新
        let count = parseInt(text.length / 20);
        if (this.editorContentCount !== count) {
          //编辑器只做文章的更新，不做新建动作
          if (this.articleDetail.articleId) {
            // 发送请求
            let imgArr=[];
            let paramsValue = {

              'id': this.articleDetail.articleId,
              'content': (html||'').replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                if (capture.indexOf("dav-images.oss-cn-qingdao.aliyuncs.com/") == -1) {
                  return "";
                } else {
                  imgArr.push(capture);
                  return match;
                }
              }),
              'origContent': (text||'').replace(/\r\n/g, "").replace(/\n/g, ""),
              'title': this.previewInfo.title

            };
            //文章标题和正文不能同时为空
            if (!paramsValue.title && !paramsValue.content) {
              return;
            }
            //把文章中的图片单独提出来提交上去
            paramsValue["images"]=imgArr.join(",");
            util.ajax.post(`/article/update`, {...paramsValue}).then((res) => {
              // 看是否操作成功还是失败
              this.editorContentCount = count;
            });
          }
        }
      },
      handerTitleBlur() {
        // localStorage.setItem('title', this.title)
        if (!this.title) {
          this.title = this.titlePlaceholder;
        }
        this.haddleSetPreviewInfo({
          title: this.title
        });

      },
      //处理文章标题焦点获取到
      handleTitleFocus() {
        if (this.title === this.titlePlaceholder) {
          this.title = "";
        }
      }
    },
    mounted() {
      let vm = this;
      this.$nextTick(() => {
        // 添加图片素材
        let qlToolbar = document.getElementsByClassName("ql-toolbar")[0];
        let buttonDom = document.createElement("span");
        buttonDom.innerHTML = '<a><svg class="icon" aria-hidden="true"><use xlink:href="#icon-image"></use></svg></a>';
        buttonDom.style.verticalAlign = "middle";
        buttonDom.style.display = "inline-block";
        buttonDom.style.fontSize = "14px";
        buttonDom.style.color = '#DF6E3C';
        buttonDom.onclick = function () {
          vm.uploadImg('uploadFormMulti')
        };
        qlToolbar.appendChild(buttonDom)
        // 后退按钮
        let buttonDom2 = document.createElement("span");
        buttonDom2.innerHTML = '<a style="margin-left: 20px"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-corner-up-left"></use></svg></a>';
        buttonDom2.style.verticalAlign = "middle";
        buttonDom2.style.display = "inline-block";
        buttonDom2.style.fontSize = "14px";
        buttonDom2.style.color = '#DF6E3C';
        buttonDom2.onclick = function () {
          vm.$refs.newEditor.quill.history.undo();
        };
        let buttonDom3 = document.createElement("span");
        buttonDom3.innerHTML = '<a style="margin-left: 20px"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-corner-up-right"></use></svg></a>';
        buttonDom3.style.verticalAlign = "middle";
        buttonDom3.style.display = "inline-block";
        buttonDom3.style.fontSize = "14px";
        buttonDom3.style.color = '#DF6E3C';
        buttonDom3.onclick = function () {
          vm.$refs.newEditor.quill.history.redo();
        };
        // 前进按钮
        qlToolbar.appendChild(buttonDom)
        qlToolbar.appendChild(buttonDom2)
        qlToolbar.appendChild(buttonDom3)
        console.log(document.querySelector('.ql-tooltip>input'))
        document.querySelector('.ql-tooltip>input').removeAttribute("placeholder")
        document.querySelector('.ql-tooltip>input').setAttribute("data-video","")
        //链接框 left 修改
        document.querySelector('.ql-video').addEventListener('click',function(){
        	var left = parseInt(document.querySelector('.ql-tooltip').style.left);
        	if(left<0){
        		document.querySelector('.ql-tooltip').style.left = 0+"px"
        	}
        },false);
        document.querySelector('.ql-link').addEventListener('click',function(){
        	var left = parseInt(document.querySelector('.ql-tooltip').style.left);
        	if(left<0){
        		document.querySelector('.ql-tooltip').style.left = 0+"px"
        	}
        },false);
        
      });
      let imgHandler = async function (image) {
        vm.addImgRange = this.$refs.newEditor.quill.getSelection()
      };
      this.$refs.newEditor.quill.getModule("toolbar").addHandler("image", imgHandler);
      this.$refs.newEditor._options.modules.toolbar[7] = [{'size': ['small', false, 'large', 'huge', '31231']}]
    },
  }
</script>

<style lang="scss" scoped>
  @import "@/assets/css/style.scss";

  .aside-right {
    position: absolute;
    top: 83px;
    left: 522px;
    right: 0px;
    bottom: 0px;
    /*min-width:890px;*/
    background: $colorWhite;
    .nocontent-tips {
      p {
        margin-bottom: 20px;
        font-size: $fs24;
        color: $listTitleColor;
      }
    }
    .aside-right_null {
      margin: 0 auto;
      width: 160px;
      line-height: 40px;
      font-size: $fs20;
      text-align: center;
      color: $listTitleColor;
      border: 1px solid $listborderColor;
      border-radius: 20px;
      background: $colorWhite;
      cursor: pointer;
    }
    .aside-right_write {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      .aside-right_header {
        padding: 15px 20px;
        input {
          line-height: 38px;
          font-size: $fs24;
          color: $listTitleColor;
          border: none;
          width: 80%;
        }
        span {
          right: 60px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .set-scale {
          float: right;
          text-align: center;
          width: 40px;
          height: 40px;
          background: #F8F8F8;
          border: 1px solid $listborderColor;
          line-height: 40px;
          border-radius: 50%;
          .icon {
            color: $vfConcentColor;
          }
        }
      }
      .quill-box {
        margin-bottom: 80px;
        flex: 1;
        display: flex;
        overflow: hidden;
      }
    }
  }

</style>
